package com.caimiao.miao.library.push;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.caimiao.miao.MiaoApplication;
import com.caimiao.miao.bean.TicketOut;
import com.caimiao.miao.http.rxjava.transformer.SchedulerTransformer;
import com.caimiao.miao.library.utils.sys.DeviceUtil;
import com.caimiao.miao.library.utils.tip.ToastUtil;
import com.caimiao.miao.page.ticket.TicketActivity;
import com.google.gson.Gson;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.entity.UMessage;
import com.umeng.message.tag.TagManager;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

///友盟推送
public class PushControl extends UmengMessageHandler {
    private static final String TAG = PushControl.class.getSimpleName();
    private static PushControl instance;
    PushAgent mPushAgent;

    public static PushControl getInstance() {
        if (instance == null)
            instance = new PushControl();
        return instance;
    }

    private PushControl() {
    }

    private IUmengRegisterCallback callback = new IUmengRegisterCallback() {
        @Override
        public void onSuccess(String s) {
            //注册成功会返回device token
            Log.e(TAG, "push_token: " + s);
            setAlias(DeviceUtil.getDeviceId(MiaoApplication.getContext()));
        }

        @Override
        public void onFailure(String s, String s1) {
            //注册失败
            Log.e(TAG, "push_token: " + s);
            ToastUtil.show("友盟推送注册失败。");
        }
    };

    //尽量在Application中调用
    public void init(Context context) {
        UMConfigure.init(context, UMConfigure.DEVICE_TYPE_PHONE, "17fc3bcc7d1d7180b1925977e48db4bc");
        mPushAgent = PushAgent.getInstance(context);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(callback);
        //监听：负责处理消息，包括通知和自定义消息
        mPushAgent.setMessageHandler(this::dealWithCustomMessage);
        //设置LOG开关，默认为false
        UMConfigure.setLogEnabled(true);
    }

    //统计应用启动数据
    public void onAppStart(Context context) {
        PushAgent.getInstance(context).onAppStart();
    }

    //关闭免打扰
    public void setNoDisturbMode() {
        ///int startHour, int startMinute, int endHour, int endMinute
        mPushAgent.setNoDisturbMode(0, 0, 0, 0);//关闭免打扰
    }

    //添加用户标签
    public void addTag(String... tags) {
        mPushAgent.getTagManager().addTags(new TagManager.TCallBack() {
            @Override
            public void onMessage(boolean b, ITagManager.Result result) {
                //isSuccess表示操作是否成功
            }
        }, tags);
    }

    //删除用户标签
    public void deleteTag(String... tags) {
        mPushAgent.getTagManager().deleteTags(new TagManager.TCallBack() {
            @Override
            public void onMessage(boolean b, ITagManager.Result result) {

            }
        }, tags);
    }

    //设置用户id和device_token的一对多的映射关系
    public void addAlias(String alias) {
        mPushAgent.addAlias(alias, "deviceid", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {

            }
        });
    }

    public void setAlias() {
        setAlias(DeviceUtil.getDeviceId(MiaoApplication.getContext()));
    }

    //设置用户id和device_token的一一映射关系，确保同一个alias只对应一台设备
    public void setAlias(final String alias) {
        String token = mPushAgent.getRegistrationId();
        if (TextUtils.isEmpty(token)) {
            ToastUtil.show("友盟推送未初始化完成，请稍后设置别名");
            return;
        }
        mPushAgent.setAlias(alias, "deviceid", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {
                Log.e(TAG, "setAlias, result = " + b + ", alias = " + s);
                if (!b) {
                    //添加失败，延迟3秒后重新设置
                    Disposable disposable = Observable.just(alias)
                            .delay(3, TimeUnit.SECONDS)
                            .compose(SchedulerTransformer.applyIoAndUi())
                            .subscribe(new Consumer<String>() {
                                @Override
                                public void accept(String s) throws Exception {
                                    setAlias(alias);
                                }
                            });
                }
            }
        });
    }

    @Override
    public void dealWithCustomMessage(Context context, UMessage uMessage) {
        Log.e(TAG, "msg: " + uMessage.custom);
        //自定义内容处理
        ToastUtil.show("开始出票");
        try {
            TicketOut pay = new Gson().fromJson(uMessage.custom, TicketOut.class);
            Intent intent = new Intent(context, TicketActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(TicketActivity.EXTRA_DATA, pay);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
